/// @Classname : HcGrid
/// @Author :
/// @Time : 2023-09-26 13:32
/// @Description : 自适应高度的宫格排列
import 'package:flutter/material.dart';
import 'package:hc_ui/widget/divider/hc_divider.dart';

class HcGrid extends StatelessWidget {
  //条目构造器
  final IndexedWidgetBuilder itemBuilder;

  //每行显示条目数
  final int crossAxisCount;

  //总条目
  final int itemCount;

  //横轴间距
  final double mainAxisSpacing;

  //次轴间距
  final double crossAxisSpacing;

  //分隔符颜色
  final Color dividerColor;

  //
  final EdgeInsets? padding;

  //分隔符样式
  final HcDividerStyle dividerStyle;

  //分隔符厚度
  final double dividerThickness;
  final double leftIndent;
  final double rightIndent;

  const HcGrid(
      {super.key,
      required this.itemBuilder,
      required this.crossAxisCount,
      this.mainAxisSpacing = 0.0,
      this.crossAxisSpacing = 0.0,
      this.padding,
      required this.itemCount,
      this.dividerStyle = HcDividerStyle.solid,
      this.dividerColor = Colors.transparent,
      this.dividerThickness = 0.0,
      this.leftIndent = 0.0,
      this.rightIndent = 0.0});

  @override
  Widget build(BuildContext context) {
    return ScrollConfiguration(
        behavior: const ScrollBehavior().copyWith(overscroll: false),
        child: ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: padding,
            itemBuilder: (itemContainer, index) =>
                _buildRow(itemContainer, index),
            separatorBuilder: (context, index) => HcDivider(
                  indent: leftIndent,
                  endIndent: rightIndent,
                  decoration: Axis.horizontal,
                  spacing: mainAxisSpacing,
                  style: dividerStyle,
                  thickness: dividerThickness,
                  color: dividerColor,
                ),
            itemCount: (itemCount / crossAxisCount).ceil()));
  }

  Widget _buildRow(BuildContext context, int index) {
    if (crossAxisCount == 1) {
      return itemBuilder(context, index);
    }
    List<Widget> row = List.empty(growable: true);
    for (int i = 0; i < crossAxisCount; i++) {
      int current = i + (index * crossAxisCount);
      row.add(Flexible(
        flex: 1,
        child: current < itemCount
            ? itemBuilder(context, current)
            : const SizedBox(),
      ));
      //加入分割线
      if (i < crossAxisCount - 1 && current <= itemCount) {
        row.add(HcDivider(
          spacing: crossAxisSpacing,
          style: dividerStyle,
          decoration: Axis.vertical,
          color: current < itemCount ? dividerColor : Colors.transparent,
          thickness: dividerThickness,
        ));
      }
    }
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: row,
      ),
    );
  }
}
